package com.ruicar.afs.cloud.channel.mange.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.channel.common.service.ChannelApproveRecordService;
import com.ruicar.afs.cloud.channel.mange.condition.ChannelUserCondition;
import com.ruicar.afs.cloud.channel.mange.entity.ChannelAppertainRegion;
import com.ruicar.afs.cloud.channel.mange.entity.ChannelUser;
import com.ruicar.afs.cloud.channel.mange.entity.ChannelUserAppertain;
import com.ruicar.afs.cloud.channel.mange.entity.ChannelUserAuthorize;
import com.ruicar.afs.cloud.channel.mange.enums.RegionLevel;
import com.ruicar.afs.cloud.channel.mange.service.ChannelAppertainRegionService;
import com.ruicar.afs.cloud.channel.mange.service.ChannelUserAppertainService;
import com.ruicar.afs.cloud.channel.mange.service.ChannelUserAuthorizeService;
import com.ruicar.afs.cloud.channel.mange.service.ChannelUserService;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xudongdong
 * @date 2020-06-03
 */
@RestController
@AllArgsConstructor
@RequestMapping("/channelUser")
@Api(value = "channelUser", description = "用户管理模块")
public class ChannelUserController {

    private final ChannelUserService userService;

    private final ChannelUserAuthorizeService userAuthorizeService;

    private final ChannelUserAppertainService userAppertainService;

    private final ChannelApproveRecordService channelApproveRecordService;

    private final ChannelAppertainRegionService channelAppertainRegionService;

    @PostMapping("/getUserListData")
    @ApiOperation(value = "多条件分页获取用户列表")
    public IResponse<IPage<ChannelUser>> getUserListData(@RequestBody QueryCondition<ChannelUserCondition> user) {
        IPage<ChannelUser> userList = userService.page(new Page(user.getPageNumber(), user.getPageSize())
                , Wrappers.<ChannelUser>query().lambda()
                        .like(StringUtils.isNotEmpty(user.getCondition().getUserRealName()), ChannelUser::getUserRealName, user.getCondition().getUserRealName()));
        for (ChannelUser u : userList.getRecords()) {
            // 关联所属区域
            List<ChannelAppertainRegion> appertainList = userService.findAppertainByUserId(u.getUserId());
            u.setAppertainRegion(appertainList);
            // 关联授权区域
            List<ChannelAppertainRegion> authorizeList = userService.findAuthorizeByUserId(u.getUserId());
            u.setAuthorizeRegion(authorizeList);

        }
        return IResponse.success(userList);
    }

    /**
     * @param userCondition
     * @return
     */
    @PostMapping("/editUser")
    @ApiOperation(value = "修改用户资料")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> edit(@RequestBody ChannelUserCondition userCondition) {

        if (!userService.update(userCondition, Wrappers.<ChannelUser>query().lambda().eq(ChannelUser::getUserId,
                userCondition.getUserId()))) {
            return IResponse.fail("修改失败");
        }
        //删除该用户所属区域
        userAppertainService.remove(Wrappers.<ChannelUserAppertain>query().lambda().
                eq(ChannelUserAppertain::getUserId, userCondition.getUserId()));
        //新所属区域
        if (userCondition.getAppertainRegionId() != null && userCondition.getAppertainRegionId().length > 0) {
            List<ChannelAppertainRegion>  app=channelAppertainRegionService.list(Wrappers.<ChannelAppertainRegion>query().lambda().in(ChannelAppertainRegion::getId,userCondition.getAppertainRegionId()));
            if(app.size()>0){
                for (ChannelAppertainRegion appertainRegion:app ){
                    if(RegionLevel.REGION_LEVEL_ONE.equals(appertainRegion.getLevel().toString())){
                        //  说明是全国那么不可以赋值给人
                        throw new AfsBaseException("添加失败,第一层级不可以赋值！");
                    }else if(RegionLevel.REGION_LEVEL_TWO.equals(appertainRegion.getLevel().toString())){
                        // 去看看这个大区是不是已经有人了
                        List<ChannelUserAppertain> us=userAppertainService.list(Wrappers.<ChannelUserAppertain>query().lambda().eq(ChannelUserAppertain::getAppertainRegionId,appertainRegion.getId()));
                        if(us.size()>0){
                            // 说明这个大区已经有人了 不可再加了
                            return IResponse.fail("添加失败,大区不可以赋值多人！");
                        }
                    }

                }
            }
            for (Long appertainRegionId : userCondition.getAppertainRegionId()) {
                ChannelUserAppertain userAppertain = new ChannelUserAppertain();
                userAppertain.setUserId(userCondition.getUserId());
                userAppertain.setAppertainRegionId(appertainRegionId);
                userAppertainService.save(userAppertain);
            }
        }
        //删除该用户所属区域
        userAuthorizeService.remove(Wrappers.<ChannelUserAuthorize>query().lambda().
                eq(ChannelUserAuthorize::getUserId, userCondition.getUserId()));
        //新授权区域
        if (userCondition.getAuthorizeRegionId() != null && userCondition.getAuthorizeRegionId().length > 0) {
            List<ChannelAppertainRegion>  app=channelAppertainRegionService.list(Wrappers.<ChannelAppertainRegion>query().lambda().in(ChannelAppertainRegion::getId,userCondition.getAuthorizeRegionId()));
            if(app.size()>0){
                for (ChannelAppertainRegion appertainRegion:app ){
                    if(RegionLevel.REGION_LEVEL_ONE.equals(appertainRegion.getLevel().toString())){
                        //  说明是全国那么不可以赋值给人
                        throw new AfsBaseException("添加失败,大区不可以赋值多人");
                    }

                }
            }
            for (Long userAuthorizeId : userCondition.getAuthorizeRegionId()) {
                ChannelUserAuthorize userAuthorize = new ChannelUserAuthorize();
                userAuthorize.setUserId(userCondition.getUserId());
                userAuthorize.setAuthorizeRegionId(userAuthorizeId);
                userAuthorizeService.save(userAuthorize);
            }
        }
        return IResponse.success(Boolean.TRUE).setMsg("操作成功");
    }

    @PostMapping("/addUser")
    @ApiOperation(value = "添加用户")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> adduser(@RequestBody ChannelUserCondition userCondition) {
        ChannelUser user=userService.getOne(Wrappers.<ChannelUser>query().lambda().eq(ChannelUser::getUserId,userCondition.getUserId()));
        if(user!=null){
            return IResponse.fail("该用户已有授权区域，请修改！");
        }
        if (!userService.save(userCondition)) {
            return IResponse.fail("添加失败");
        }
        // 声明一个判断 ，主要是判断  大区只能加给一个人  并且

        //添加所属区域
        if (userCondition.getAppertainRegionId() != null && userCondition.getAppertainRegionId().length > 0) {
            List<ChannelAppertainRegion>  app=channelAppertainRegionService.list(Wrappers.<ChannelAppertainRegion>query().lambda().in(ChannelAppertainRegion::getId,userCondition.getAppertainRegionId()));
            if(app.size()>0){
                for (ChannelAppertainRegion appertainRegion:app ){
                    if(RegionLevel.REGION_LEVEL_ONE.equals(appertainRegion.getLevel().toString())){
                        //  说明是全国那么不可以赋值给人
                        throw new AfsBaseException("添加失败,第一层级不可以赋值！");
                    }else if(RegionLevel.REGION_LEVEL_TWO.equals(appertainRegion.getLevel().toString())){
                       // 去看看这个大区是不是已经有人了
                        List<ChannelUserAppertain> us=userAppertainService.list(Wrappers.<ChannelUserAppertain>query().lambda().eq(ChannelUserAppertain::getAppertainRegionId,appertainRegion.getId()));
                        if(us.size()>0){
                            // 说明这个大区已经有人了 不可再加了
                            throw new AfsBaseException("添加失败,大区不可以赋值多人");
                        }
                    }

                }
            }
            for (Long appertainRegionId : userCondition.getAppertainRegionId()) {

                ChannelUserAppertain userAppertain = new ChannelUserAppertain();
                userAppertain.setUserId(userCondition.getUserId());
                // 这一步去判断选中的区
                userAppertain.setAppertainRegionId(appertainRegionId);
                userAppertainService.save(userAppertain);
            }
        }
        //添加授权区域
        if (userCondition.getAuthorizeRegionId() != null && userCondition.getAuthorizeRegionId().length > 0) {
            List<ChannelAppertainRegion>  app=channelAppertainRegionService.list(Wrappers.<ChannelAppertainRegion>query().lambda().in(ChannelAppertainRegion::getId,userCondition.getAuthorizeRegionId()));
            if(app.size()>0){
                for (ChannelAppertainRegion appertainRegion:app ){
                    if(RegionLevel.REGION_LEVEL_ONE.equals(appertainRegion.getLevel().toString())){
                        //  说明是全国那么不可以赋值给人
                        return IResponse.fail("添加失败,第一层级不可以赋值！");
                    }

                }
            }
            for (Long userAuthorizeId : userCondition.getAuthorizeRegionId()) {
                ChannelUserAuthorize userAuthorize = new ChannelUserAuthorize();
                userAuthorize.setUserId(userCondition.getUserId());
                userAuthorize.setAuthorizeRegionId(userAuthorizeId);
                userAuthorizeService.save(userAuthorize);
            }
        }
        return IResponse.success(Boolean.TRUE).setMsg("操作成功");
    }

    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过ids删除")
    @Transactional
    @SysLog("批量通过ids删除")
    public IResponse<Boolean> delAllByIds(@PathVariable Long[] ids) {

        for (Long id : ids) {
            userService.remove((Wrappers.<ChannelUser>query().lambda().
                    eq(ChannelUser::getUserId, id)));
            //删除该用户所属区域
            userAppertainService.remove(Wrappers.<ChannelUserAppertain>query().lambda().
                    eq(ChannelUserAppertain::getUserId, id));
            //删除该用户所属区域
            userAuthorizeService.remove(Wrappers.<ChannelUserAuthorize>query().lambda().
                    eq(ChannelUserAuthorize::getUserId, id));
        }
        return new IResponse<Boolean>().setMsg("批量通过id删除数据成功");
    }
}
